package band.wukong.practice.java.core.topic.concurrency.threadpool;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * CompletableFuture Sample 4 Method Compelte
 * Refer: http://blog.163.com/pilgrim_yang/blog/static/55631481201521105257879/
 *
 * @author wukong(wukonggg@139.com)
 */
public class CompletableFutureSample4MethodCompelte {

    public static void main(String[] args) {
        CompletableFuture<String> future = ask();
        Thread t1 = new TestThread(future), t2 = new TestThread(future);
        t1.start();
        t2.start();
        try {
            Thread.sleep(2000);
            System.out.println("2 secs later, about to complete future with 42");
            future.complete("42");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static CompletableFuture<String> ask() {
        final CompletableFuture<String> future = new CompletableFuture<>();
        //...
        return future;
    }
}

class TestThread extends Thread {

    private CompletableFuture<String> future = null;

    public TestThread(CompletableFuture<String> future) {
        this.future = future;
    }

    public void run() {
        System.out.println("start block get.");

        String s = null;
        try {
            s = future.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println("exit block get and [" + s + "].");
    }
}
